package cn.lixin.user.service.impl;

import cn.lixin.basic.exception.BusinessException;
import cn.lixin.basic.utils.AjaxResult;
import cn.lixin.basic.utils.HttpClientUtils;
import cn.lixin.basic.utils.MD5Utils;
import cn.lixin.basic.utils.StrUtils;
import cn.lixin.user.contain.UserConstants;
import cn.lixin.user.domain.LoginDto;
import cn.lixin.user.domain.Logininfo;
import cn.lixin.user.domain.User;
import cn.lixin.user.domain.WxUser;
import cn.lixin.user.mapper.LogininfoMapper;
import cn.lixin.user.mapper.UserMapper;
import cn.lixin.user.mapper.WxUserMapper;
import cn.lixin.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 实现登录
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //校验 1 空
        if (StringUtils.isEmpty(loginDto.getUsername())
                || StringUtils.isEmpty(loginDto.getPassword())
                || StringUtils.isEmpty(loginDto.getType())) {
            throw new BusinessException("信息填写不完整！");
        }
        //  2 查询是否有登录信息
        Logininfo logininfo = logininfoMapper.loadByLoginDto(loginDto);
        if (logininfo == null){
            throw new BusinessException("查无此人！请检查你的用户名或密码！");
        }
        // 查询到有这个人了，需要判断密码
        String salt = logininfo.getSalt(); // 根据信息查询salt 表中的salt
        String password = logininfo.getPassword(); // 保存在表中的密码 => 由md5处理过的 md5 = pwd + salt
        if (!password.equals(MD5Utils.encrypByMd5(loginDto.getPassword()+salt))){
            throw new BusinessException("请检查你的用户名或密码！");
        }

        // 密码正确将信息保存到redis中
        String token = UUID.randomUUID().toString(); // 设置token 一定要toString
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES); // 对象必须在domain中序列化 设置30分钟的redis缓存
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        // 由于前端可以查看请求头，所以为了安全我们可以置空密码
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;

    }

    @Override
    public AjaxResult wechat(Map<String,String> params){
        // 获取code
        String code = params.get("code");
        if (!StringUtils.hasLength(code)){
            throw new BusinessException("没有授权码");
        }

        // 去微信获取令牌
        // 携带code获取token - 需要后端按照指定格式发起httpClient请求
        String getTokenUrl = UserConstants.WXUSER_GET_TOKEN_URL.replace("APPID", UserConstants.APPID)
                .replace("SECRET", UserConstants.SECRET)
                .replace("CODE", code);

        // 微信会返回一个json格式的字符串
        String jsonTemp = HttpClientUtils.httpGet(getTokenUrl);
        // 转换为json对象拿数据
        JSONObject jsonObject = JSONObject.parseObject(jsonTemp);
        String accessToken = jsonObject.getString("access_token"); // 这个就是令牌
        String openId = jsonObject.getString("openid"); //存在数据库的openid

        // 如果该openid在表中，说明不是第一次登录了，直接免密
        // 根据openid查询是否在表中
        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        if (wxUser != null && wxUser.getUser_id() != null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxUser.getUser_id());
            String token = UUID.randomUUID().toString();
            // 存到redis
            redisTemplate.opsForValue().set(token,logininfo,3,TimeUnit.MINUTES);
            // 将信息返回给前端
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            // 置空数据
            logininfo.setPassword(null);
            logininfo.setSalt(null);
            map.put("logininfo",logininfo);
            return AjaxResult.me().setResultObj(map);
        }
        // 如果该openid不在表中，说明是第一次登录了，需要绑定 - 拼接成需要发送请求的格式
        String binderUrlParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.me().setResultObj(binderUrlParams).setSuccess(false);
    }

    @Override
    public Map<String ,Object> binder( Map<String ,String> params){
        // 校验 -空
        String phone = params.get("phone");
        String verifyCode = params.get("verifyCode");
        String accessToken = params.get("accessToken");
        String openId = params.get("openId");
        if (!StringUtils.hasLength(phone) || !StringUtils.hasLength(verifyCode)
            || !StringUtils.hasLength(accessToken) || !StringUtils.hasLength(openId) ){
            throw new BusinessException("信息填写不完整！");

        }
        // 校验 - 验证码过期
        Object codeTmp = redisTemplate.opsForValue().get(UserConstants.BUSINESS_BINDER_PREFIX+phone);
        if (codeTmp == null){
            throw new BusinessException("验证码过期");
        }
        // 校验 - 验证码是否相同
        String code = codeTmp.toString().split(":")[0];
        if (!code.equalsIgnoreCase(verifyCode)){
            throw new BusinessException("验证码错误");
        }
        // 校验 - 手机号是否注册
        User userTemp = userMapper.loadByPhone(phone);
        User user = null; // 最终存放在表的user
        Logininfo logininfo = null; // 最终存放在redis中的
        if (userTemp != null){
            user = userTemp;
            logininfo = logininfoMapper.loadByUserId(user.getLogininfo_id());
        }else { // 真正的新用户 只有手机号
            user = initUser(phone);
            logininfo = user2logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);
        }
        // 通过token 和openId获取用户信息
        String getUserUrl = UserConstants.WXUSER_GET_USER_URL.replace("ACCESS_TOKEN",accessToken)
                .replace("OPENID",openId);
        String wxUserTemp  = HttpClientUtils.httpGet(getUserUrl);
        WxUser wxUser = initWxUser(wxUserTemp,user);// 传入user是因为要绑定userId
        wxUserMapper.save(wxUser);

        // 登录 - 保存到redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,3,TimeUnit.MINUTES);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        // 置空信息
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;
    }

    private WxUser initWxUser(String wxUserTemp, User user) {
        /*
           "openid":"OPENID",
            "nickname":"NICKNAME",
            "sex":1,
            "province":"PROVINCE",
            "city":"CITY",
            "country":"COUNTRY",
            "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
            "privilege":[
            "PRIVILEGE1",
            "PRIVILEGE2"
            ],
            "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
         */
        JSONObject jsonObject = JSONObject.parseObject(wxUserTemp);
        WxUser wxUser = new WxUser();
        wxUser.setUser_id(user.getId());
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setNickname(jsonObject.getString("nickname"));
        wxUser.setUnionid(jsonObject.getString("unionid"));
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setAddress(null);
        return wxUser;

    }

    private Logininfo user2logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User initUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5 = MD5Utils.encrypByMd5("1234" + salt);
        user.setPassword(md5);
        return user;
    }
}
